package com.vgooo.client.mobile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.Brand;
import com.vgooo.bean.ProdAbstract;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.VGApplication;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.ui.MobileFragment;
import com.vgooo.client.ui.TabPageIndicator;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;

public class MobileMainFragmentActivity extends VGActivity {


	private final static String className = "MobileMainFragmentActivity";

	private List<ProdAbstract> prodsInfo;// 热门推荐手机列表
	private Map<String, List<ProdAbstract>> prods = new HashMap<String, List<ProdAbstract>>();
	private List<Brand> brands = new ArrayList<Brand>();// 品牌信息



	public final static String HOT_PROD = "推荐";


	private static int bc = 1;

	private TabPageIndicator indicatior;
	private ViewPager viewPager;

	public MobileMainFragmentActivity() {
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		// 设置缓存路径
		VGApplication appliction = (VGApplication) getApplication();
		appliction.setCaesPath(getCacheDir().toString());

		setContentView(R.layout.mobile_main_fragment);

		initView();

		init();

		brands = new ArrayList<Brand>();

		FragmentPagerAdapter fragmentAdapter = new MobileFragmentAdapter(
				getSupportFragmentManager());
		viewPager.setAdapter(fragmentAdapter);
		indicatior.setViewPager(viewPager);

	}

	public void initView() {
		indicatior = (TabPageIndicator) findViewById(R.id.brands_indicator);
		viewPager = (ViewPager) findViewById(R.id.mobiles_viewPager);
		View moreBrands = findViewById(R.id.mobile_main_brands_sort_more);
		indicatior.setMoreBrands(moreBrands);
	}

	class MobileFragmentAdapter extends FragmentPagerAdapter {
		public MobileFragmentAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			Brand brand = brands.get(position);
			Fragment mobileFragment = new MobileFragment(brand, prodsInfo,
					MobileMainFragmentActivity.this);

			return mobileFragment;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return brands.get(position % brands.size()).brand_name;
		}

		@Override
		public int getCount() {
			return brands.size();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);

		if (ViewLayout.viwStack == null || ViewLayout.viwStack.isEmpty()) {
			if (ViewLayout.viwStack == null) {
				ViewLayout.viwStack = new Stack<ViewLayout>();
			}
			ViewLayout.viwStack.push(new ViewLayout(true, "手机中心",
					ViewLayout.ID_TAG_MOBILE, ViewLayout.TAB_TAG_MOBILE, this));

		}

		Main.currentTabId = ViewLayout.ID_TAG_MOBILE;
		if (!isFirst && (brands == null || brands.isEmpty())) {
			// new DataSAsyncLoader(cparent).execute(null);
			init();
		} else {
			isFirst = false;
		}
		bc = 1;
		// 设置导航栏背景色
		Main.setNavBackground(ViewLayout.ID_TAG_MOBILE);
		Main.back.setVisibility(View.GONE);

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
		bc = 1;

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		MobileFragment.clearCaches();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// DebugTools.log(className, "你按下了返回键。。。。");
			switch (bc) {
			case 0:
				// ViewLayout.setViewBack(this);
				Main.isFist = true;
				ViewLayout.viwStack.clear();
				this.finish();
//				Main.activity.finish();
				System.gc();
				break;

			case 1:
				Toast.makeText(this, "再按一次退出!", Toast.LENGTH_SHORT).show();
				bc--;
				break;
			}
		}
		return true;
	}

	@Override
	public void setupView() {

		indicatior.notifyDataSetChanged();

	}

	@Override
	public void addListener() {
		// TODO Auto-generated method stub
	}

	@Override
	public void flashView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void getData() {
		// TODO Auto-generated method stub
		try {
			String urlPath = HttpUtils.BASE_URI + "hotprod";

			prodsInfo = getHotProd(urlPath);

			// prods.put(HOT_PROD, prodsInfo);

			brands = getBranchs();

			MobileAdapter.setBrands(brands, prodsInfo);

			// new DownLaodData().execute(null);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	@Override
	public void doClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		switch (v.getId()) {

		default:
			log("doClick() : 未定义单击后触发的事件");
			break;
		}
	}

	public static ArrayList<Brand> getBranchs() throws Exception {
		String urlPath = HttpUtils.BASE_URI + "brands";
		String jsonString = HttpUtils.getJsonString(urlPath);
		// Map<String, Object> m = GSonTools.getObjectMaps(jsonString);
		List<Map<String, Object>> list = GSonTools.getMulObjectList(jsonString);
		ArrayList<Brand> brands = new ArrayList<Brand>();
		Brand b = new Brand();
		b.brand_name = HOT_PROD;
		b.brand_id = "";
		brands.add(b);
		for (Map<String, Object> map : list) {
			Brand brand = new Brand();
			brand.brand_id = (String) map.get("brand_id");
			brand.brand_name = (String) map.get("brand_name");
			brands.add(brand);
		}
		urlPath = null;
		jsonString = null;
		return brands;

	}

	public static List<ProdAbstract> getHotProd(String urlPath)
			throws Exception {
		String jsonString = HttpUtils.getJsonString(urlPath);

		List<Map<String, Object>> prods = GSonTools
				.getMulObjectList(jsonString);
		List<ProdAbstract> prodInfos = new ArrayList<ProdAbstract>();
		for (Map<String, Object> map : prods) {
			ProdAbstract prod = new ProdAbstract();
			prod.brand_name = (String) map.get("brand_name");
			prod.brand_html = (String) map.get("brand_html");
			prod.prod_thumbnail = (String) map.get("prod_thumbnail");
			prod.prod_html = (String) map.get("prod_html");
			prod.prod_name = (String) map.get("prod_name");
			Map<String, Object> price = (Map<String, Object>) map.get("price");
			prod.price_sell = (String) price.get("price_sell");
			prodInfos.add(prod);
			map = null;
		}
		jsonString = null;
		prods = null;
		return prodInfos;

	}

	/**
	 * 打印调试信息
	 * 
	 * @param info
	 */
	private void log(String info) {
		// Log.i(this.getClass().getSimpleName(), info);
		DebugTools.log(className, info);
	}


}
